#!/usr/bin/perl

use strict;
use Proc::Daemon;

my $pwd = `pwd`; 
chomp $pwd;

my $PING_COMMAND = "nohup $pwd/ping-gen";
my $MON_COMMAND = "nohup $pwd/monitor";
my $PING_PID_F = "$pwd/pid/ping.pid";
my $MON_PID_F  = "$pwd/pid/mon.pid";
my $PING_LOG_F = "$pwd/log/ping.log";
my $MON_LOG_F = "$pwd/log/mon.log";


my $pingd = Proc::Daemon->new(
    work_dir => $pwd,
    pid_file => $PING_PID_F,
    child_STDOUT => "+>>$PING_LOG_F",
    child_STDERR => "+>>$PING_LOG_F",
    exec_command => $PING_COMMAND,
);
my $mond = Proc::Daemon->new(
    work_dir => $pwd,
    pid_file => $MON_PID_F,
    child_STDOUT => "+>>$MON_LOG_F",
    child_STDERR => "+>>$MON_LOG_F",
    exec_command => $MON_COMMAND
);

sub start() {
    if (getstatus() == 1) {
        print "Already started.\n";
        return;
    }

    print "Starting pings...\n";
    my $pid1 = $pingd->Init( {} );
    print "Starting monitor...\n";
    my $pid2 = $mond->Init();
}

sub stop() {
    if (getstatus() == 0) {
        print "Not running.\n";
        return;
    }

    print "Stopping pings...\n";
    my $ping_kill = $pingd->Kill_Daemon();
    print "Stopping monitor...\n";
    my $mon_kill = $mond->Kill_Daemon();
}

sub restart() {
    stop();
    start();
}

sub usage() {
    print "Usage: mcp start|stop|restart";
}

sub getstatus() {
    my $status1 = $pingd->Status();
    my $status2 = $mond->Status();
    if ($status1 > 0 && $status2 > 0) { return 1; }
    else { return 0; }
}

sub status() {
    if (getstatus() == 1) { print "running\n"; }
    else { print "stopped\n"; }
}

BEGIN: 

if (scalar @ARGV == 0) {
    usage();
    exit(1);
}

my $command = $ARGV[0];
if ($command eq "start") { start(); }
elsif ($command eq "stop") { stop(); }
elsif ($command eq "restart") { restart(); }
elsif ($command eq "status") { status(); }
else { usage(); }

